package com.company.Nio.chat;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ChatClient {
    private final String HOST = "127.0.0.1";
    private int PORT = 9999;
    private SocketChannel socketChannel;
    private String userName;

    public ChatClient() {
        try {
            //得到监听通道
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            InetSocketAddress address = new InetSocketAddress(HOST, PORT);
            if (!socketChannel.connect(address)) {
                while (!socketChannel.finishConnect()) {
                    System.out.println("Client：连接服务器的同时做其他事");
                }
            }

            userName = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println("----------Client(" + userName + ") is ready-----------");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //向服务端发送消息
    public void sendMsg(String msg) throws Exception {
        if ("bye".equalsIgnoreCase(msg)) {//结束聊天
            socketChannel.close();
            return;
        }
        msg = userName + "说___:" + msg;
        ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
        socketChannel.write(wrap);
    }

    //接受服务端的消息
    public void receiveMsg() throws Exception {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int read = socketChannel.read(buffer);
        if (read > 0) {
            String msg = new String(buffer.array());
            System.out.println(msg.trim());
        }

    }

}
